﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;


namespace AspxImageGallery
{
    public partial class Default : System.Web.UI.Page
    {
        public int CurrentPage
        {
            get
            {
                int currentPage = 1;
                if (Request.QueryString["page"] != null)
                {
                    currentPage = int.Parse(Request.QueryString["page"]);
                }
                return currentPage;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {            
                BindGallery();
                BuildPaging();
            }
        }

        private void BuildPaging()
        {
            litPages.Text = "Pages  ";
            int totalFiles = (new DirectoryInfo(Server.MapPath("~/Photos/Gallery"))).GetFiles("*.jpg").Count();
            List<int> pages = new List<int>();
            int totalPages = totalFiles / 20 + (totalFiles % 20 == 0 ? 0 : 1);
            for (int i = 1; i <= totalPages; i++)
            {
                if (i != CurrentPage)
                {
                    litPages.Text += string.Format(" [<a href='/Default.aspx?page={0}' title='{0} of {1} pages'>{0}</a>] ", i, totalFiles);
                }
                else
                {
                    litPages.Text += string.Format(" [<a href='/Default.aspx?page={0}' title='{0} of {1} pages' style='color:red; font-size:30px;'>{0}</a>] ", i, totalFiles);
                }
            }
        }

        private void BindGallery()
        {
            var files = (new DirectoryInfo(Server.MapPath("~/Photos/Gallery"))).GetFiles("*.jpg");
            int totalFiles = files.Count();
            int pageSize = 20;
            int pagesToSkip = (CurrentPage - 1) * pageSize;
            if (files.Any())
            {
                //
                rptGallery.DataSource = files.Skip(pagesToSkip).Take(pageSize)
                        .Select((f, index) => new
                        {
                            Name = f.Name,
                            Description = string.Format("{0} out of {1} photos", (pagesToSkip + index + 1), totalFiles)
                        })
                        .OrderBy(f => f.Name);
                rptGallery.DataBind();
            }
        }
    }
}